package com.yunupmall.service.ford.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunupmall.api.fordVO.AddressVo;
import com.yunupmall.api.fordVO.OrderVo;
import com.yunupmall.api.fordentity.*;
import com.yunupmall.api.po.OrderByidPo;
import com.yunupmall.api.po.OrderPagePO;
import com.yunupmall.api.po.OrderbyidCommtityPo;
import com.yunupmall.api.po.SteamShopingDataPO;
import com.yunupmall.entity.admin.memberpojo.Member;
import com.yunupmall.mapper.FordMapper.ExpandOrderMapper;
import com.yunupmall.mapper.FordMapper.OrderMapper;
import com.yunupmall.service.admin.impl.Memberimpl;
import com.yunupmall.service.admin.service.CommodityService;
import com.yunupmall.service.admin.service.MemberService;
import com.yunupmall.service.admin.service.SpecsCommdityService;
import com.yunupmall.service.ford.service.*;
import com.yunupmall.uits.AlipayConfig;
import com.yunupmall.uits.Result;
import com.yunupmall.uits.SessionUtis;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.DateUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class Orderimpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final ExpandOrderService expandOrderService;
    private final CommodityService commodityService;
    private final ShopingService shopingService;
    private final SpecsCommdityService specsCommdityService;
    private final PayService payService;
    private final Result result;
    private final AddressService addressService;
    private final ExpandOrderMapper expandOrderMapper;
    private final FordMemberService fordMemberService;
    private final SaleService saleService;
    private final EvaluateService evaluateService;


    private final String APP_ID = "2021000119644933";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJSouxFgBpNgoaR5DwbJmA1Y3KjOQg0vguUimgHRqQwviqkWcrX4HqadOS9L8wDukM2EcyY77BNMeyxW8ZUPM+4kEb5WmhLgpERjZsGLC1lWTfCZ8sVG9mpO5F5rWqPkds5EHFsR2epeVn4KC6X0FjCDmOI9d1QEkEb1N/mWB1WgkNsCLwv2aCKCGdFt6IecSTR2OEzE4JJif8ZvA0MwjTwbYOn3bimuH7ekt4pN+yqQ20pHCHXtWfrcartCyaCvVr43yJQt19yu18+gerPTjc64kyvNFgepRAycvizIgHgaLpLkroBG3XaY+W0K51SGw0KwQ7LLpx0vibYPCjqaT3AgMBAAECggEBAIB1cnCw+dIrCod65KSKqevuXW7GO1A3Uus8xBPKfwmjY852vMCRUvemUb+XMewZl+D6pXUi8rmaVVdhaGVfo9ydx69l2ONj3mlz5YdWum8nyBgOq+Y+fFmlJ+q0MXtUA4Eaql7fiWeVt7FzSR+narMorJJpjTbmr7KE2WS1HTnF+frIQsJgvOLKvngqzfM5emSvgXrQqvb7Hpc3udXlX1b3ouxXEAbSI6m2mkUytcuTHlcxKjWsQvvunE7JGsa1Z+Wx/qHLBssDbSdfqXnm/rPPbQtSUCjURl0t2U9KdwxcAd62hPwNFcQMsjaZOOybqLpYtV5kGZ238KIH2c1tSwECgYEA5pCv0F7jcleQFKDAkZgkdh1OqdnW8VLynkuQ0l1HJg6Jy/wFotZTuGCWxUxqNZd5hHN14Yy1UhsOpQXIeJUiO6XA1lBHgeNXWhHguMBV3WZ9IeO/JJHpLzGPm8uLUJI7xPllihbbxrelalt64TGdZ05va15pmIb3YOpmTS9TclUCgYEA338kYJtvcnracUCjb2x35E+3dp4drPiQP1gq0r0SV4fFXmTnBc+9y2rvpMECexu3/uiN8BaIpx2u2TFYjCk91srfosWOZwZP+cqarJUDN0I+aRqAivOPV9RX0nu2TqBxdWAQOPdwO0qldCWGFhd4vwiWrXumx86LlyP/89N8PhsCgYEAyAnoQATTmTTXUM5XxPoXSFMNGNhjYGTzEtvE/n7nZ+FdNJmn2ivR3zoOFYfC7lRJndz+/X2zI1VOU2a9E8FwPggFUuu73rl75C12p1RYKwrsriaGhBgEFGoPisACUxlMug0XR8OlUreq0Kgl6JO/WQ34JVN4klkm7/LuZzEUWTECgYAF8M04vCj0NAvGYt91QL7XFL9dqcpEJL9Az8kjnN718KfwYGI7p0/2Ljt8d5znRM9ZOTk8nny3ZHSXVVZzM01vfij/nJyyZFqP2zDNUZCqUVpzVL8B8oNm5EAJWjx4To91fT4xJXKYQN2w/qZXw/vzp/jJV7YRLY5MUCqngoGU7QKBgD7IbsATbsqix/JEWGbSZ/8DzD/PsS0ePk8M4YBbqJgD9X6K2jGeHDt97vu1aTk4FCgjA1JADl0vzRirLvwJvYvd1lFilc3W8JAdV3yXNlkqFaAD2HyPRberL4fNgyiCIvqmliXSQK/zWE2na+p35D51dw+KuTzsy1k+48L6iyd5";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg//3meVzoOeC5E/M1TTwtyC+IV62DprhqAy6UC9VKlqNJlcdnfN2Y01QBanDaCFmN8IFA2cy5mff/X86tH4GQ58ful/e1MhBM2jkSdjdgQ5060ksI3A8/r3Ic/cl77Dow7+J51uSXMI9mr1xbZVDyUMsHtdbAH9Eue31osPzrOaPxljg8jk02SfA6xiSSpyWytvgXZLLNnp1brPC0/tAwxAz9nkBGyWfhu/vEqkmNAIf/9mVfJGnvmJnXxSTI4aaJGkRslJD7g4RfRXtXACkuRUWptIFFtHo7hTAIZuohPyynK7oMuv3hK0pt18Y0AnI3xEv94qwilrZVd+9lqfevwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://50p71z4960.qicp.vip/order/returnOrderData";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://192.168.0.104:8888/skippage?url=udai_order";
    /**
     * 新增订单
     * @param orderVo
     * @return
     */
    @Override
    @Transactional
    public Result saveData(OrderVo orderVo) throws UnsupportedEncodingException {
        if (ObjectUtil.isEmpty(orderVo.getSteamShopingDataPO())){
            throw new RuntimeException("商品数据为空");
        }
        Member member =(Member) SessionUtis.getSessionAttribute("member");
        if (ObjectUtil.isEmpty(member)){
            throw new RuntimeException("用户信息为空");
        }
        if (ObjectUtil.isEmpty(orderVo.getAddressId())){
            throw new RuntimeException("收货地址ID为空");
        }
        List<SteamShopingDataPO> steamShopingDataPO2 = orderVo.getSteamShopingDataPO();
        steamShopingDataPO2.forEach(steamShopingDataPO -> {
            SpecsCommodity byId = specsCommdityService.getById(steamShopingDataPO.getSpeceId());
            if (steamShopingDataPO.getCount()>byId.getStocks()){
                throw new RuntimeException("库存不足");
            }
        });
        Order order = new Order();
        BeanUtils.copyProperties(orderVo,order);
        //生成订单编号
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String date = df.format(new Date());
        int abs = Math.abs(member.getId().hashCode());
        String orderUUID=member.getId()+date+abs;
        order.setOrderUuid(orderUUID);
        order.setCreateTime(LocalDateTime.now());
        order.setDeflag(0);
        order.setOrderStatic(0);
        order.setMId(member.getId());
        //获取总价格
        final double[] price = {0};
        List<SteamShopingDataPO> steamShopingDataPO = orderVo.getSteamShopingDataPO();
        steamShopingDataPO.forEach(steamShopingDataPO1 -> {
            BigDecimal bigDecimal = new BigDecimal(steamShopingDataPO1.getCount());
            BigDecimal bigDecimal1 = new BigDecimal(steamShopingDataPO1.getPrice());
            BigDecimal multiply = bigDecimal1.multiply(bigDecimal);
            double v = multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            price[0] +=v;
        });
        order.setPrice(price[0]);
        if (!this.save(order)){
            throw new RuntimeException("订单创建失败");
        }
        Integer orderId = order.getId();
        List<ExpandOrder> expandOrderList = new ArrayList<>();

        List<SpecsCommodity> specsCommodityArrayList = new ArrayList<>();
        List<Integer> shopingArrayList = new ArrayList<>();
        final ExpandOrder[] expandOrder = new ExpandOrder[1];
        steamShopingDataPO.forEach(steamShopingDataPO1 -> {
            expandOrder[0] =new ExpandOrder();
            expandOrder[0].setCId(steamShopingDataPO1.getCId());
            expandOrder[0].setOrderId(orderId);
            expandOrder[0].setCount(steamShopingDataPO1.getCount());
            expandOrder[0].setPrces(steamShopingDataPO1.getPrice());
            expandOrder[0].setSpecsId(steamShopingDataPO1.getSpeceId());
            expandOrder[0].setDeflag(0);
            expandOrder[0].setCreateTime(LocalDateTime.now());
            SpecsCommodity specsCommodity = new SpecsCommodity();
            specsCommodity.setId(steamShopingDataPO1.getSpeceId());
            specsCommodity.setStocks(steamShopingDataPO1.getCount());
            specsCommodityArrayList.add(specsCommodity);
            shopingArrayList.add(steamShopingDataPO1.getShopingId());
            expandOrderList.add(expandOrder[0]);
        });
        if (expandOrderService.saveBatch(expandOrderList)){
            //购物车信息删除
            LambdaUpdateWrapper<Shoping> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(Shoping::getId,shopingArrayList);
            Shoping shoping = new Shoping();
            shoping.setDeflag(1);
            if (!shopingService.update(shoping, wrapper)) {
                throw new RuntimeException("购物车信息更新失败");
            }
            StringBuilder stringBuilder = new StringBuilder();
            expandOrderList.forEach(expandOrder1 -> {
                Commodity byId = commodityService.getById(expandOrder1.getCId());
                stringBuilder.append(byId.getName());
            });
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no",orderUUID);
            bizContent.put("total_amount",String.valueOf(price[0]));
            bizContent.put("subject",stringBuilder.toString());
            bizContent.put("body",stringBuilder.toString());
            bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
            String encode = URLEncoder.encode(String.valueOf(member.getId()) , "UTF-8");
            bizContent.put("passback_params", encode);
            String ailpay = ailpay(bizContent);
            if (ObjectUtil.isNotEmpty(ailpay)){
                result.setMsg(order.getOrderUuid());
                result.setData(ailpay);
                result.setCode(0);
                return result;
            }else {
                return null;
            }
        }else {
            throw new RuntimeException("创建失败");
        }
    }

    private String ailpay(JSONObject bizContent){
        try {
            //实例化客户端,填入所需参数
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //在公共参数中设置回跳和通知地址
            request.setReturnUrl(RETURN_URL);
            request.setNotifyUrl(NOTIFY_URL);
            request.setBizContent(bizContent.toString());
            String form = "";
            form = alipayClient.pageExecute(request).getBody();
            return form;
        }catch (Exception e) {
            return e.getMessage();
        }
    }

    @Override
    @Transactional
    public Integer updateDate(Order order) {
        if (ObjectUtil.isEmpty(order.getOrderUuid())){
            throw new RuntimeException("订单编号为空");
        }
        LambdaUpdateWrapper<Order> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Order ::getOrderUuid,order.getOrderUuid());
        Order order1 = new Order();
        order1.setOrderStatic(1);
        if (this.update(order1, wrapper)) {
            return 0;
        }else {
            return 1;
        }
    }

    /**
     * 支付宝付款回调
     * @param request
     * @return
     */
    @Override
    @Transactional
    public String returnData(HttpServletRequest request) {
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY,CHARSET,SIGN_TYPE); //调用SDK验证签名
            if(signVerified) {//验证成功
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
                LambdaUpdateWrapper<Order> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Order ::getOrderUuid,out_trade_no);
                Order order = new Order();
                order.setOrderStatic(1);
                if (!this.update(order,wrapper)) {
                    throw new RuntimeException("订单修改失败");
                }
                //订单库存的扣除
                LambdaUpdateWrapper<Order> wrapper1 = new LambdaUpdateWrapper<>();
                wrapper1.eq(Order ::getOrderUuid,out_trade_no);
                //该条订单信息
                Order one = this.getOne(wrapper1);
                //订单扩展表信息
                LambdaUpdateWrapper<ExpandOrder> expandOrderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                expandOrderLambdaUpdateWrapper.eq(ExpandOrder ::getOrderId,one.getId());
                List<ExpandOrder> list = expandOrderService.list(expandOrderLambdaUpdateWrapper);
                list.forEach(expandOrder -> {
                    SpecsCommodity byid = specsCommdityService.byid(expandOrder.getSpecsId());
                    byid.setStocks(byid.getStocks()-expandOrder.getCount());
                    if (!specsCommdityService.updateById(byid)){
                        throw new RuntimeException("库存变更失败");
                    }
                });
                //销量流水
                Map<Integer, List<ExpandOrder>> collectMap = list.stream().collect(Collectors.groupingBy(ExpandOrder::getCId));
                for (Map.Entry<Integer, List<ExpandOrder>> entry : collectMap.entrySet() ) {
                    List<ExpandOrder> valueList = entry.getValue();
                    Integer counts=0;
                    for (ExpandOrder expandOrder : valueList) {
                        counts+=expandOrder.getCount();
                    }
                    Sales sales = new Sales();
                    sales.setCId(valueList.get(0).getCId());
                    sales.setCounts(counts);
                    sales.setCreateTime(LocalDateTime.now());
                    if (!saleService.save(sales)){
                     throw new RuntimeException("保存失败");
                    }
                }

                //支付宝交易流水
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
                String gmt_payment = new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime ldt = LocalDateTime.parse(gmt_payment,df);
                String subject1 = params.get("subject");
                String buyer_id = params.get("buyer_id");
                String seller_id = params.get("seller_id");
                //订单号
                String out_trade_no1 = params.get("out_trade_no");
                Integer mId =Integer.parseInt(params.get("passback_params"));
                Double total_amount = Double.parseDouble(params.get("total_amount"));
                Pay pay = new Pay();
                pay.setOutTradeNo(out_trade_no1);
                pay.setTradeNo(trade_no);
                pay.setPayA(buyer_id);
                pay.setPayB(seller_id);
                pay.setSubject(subject1);
                pay.setPayTime(ldt);
                pay.setTotalAmount(total_amount);
                pay.setPatStatic(0);
                pay.setDeflag(0);
                pay.setMId(mId);
                Pay pay1 = new Pay();
                BeanUtils.copyProperties(pay,pay1);
                pay1.setPatStatic(1);
                pay1.setMId(null);
                List<Pay> pays = new ArrayList<>();
                pays.add(pay1);
                pays.add(pay);
                if (payService.saveBatch(pays)) {
                    return "处理成功";
                }else {
                    throw new RuntimeException("处理失败");
                }
            }else {//验证失败
                return "验证失败";
            }
        }catch (Exception e) {
            return "报错失败";
        }
    }

    /**
     * 异步轮询
     * @param uuid
     * @return
     */
    @Override
    public Result polling(String uuid) {
        if (ObjectUtil.isEmpty(uuid)){
            throw new RuntimeException("订单编号为空");
        }
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order ::getOrderUuid,uuid);
        List<Order> list = this.list(wrapper);
        if (list.size()!=0){
            Order order = list.get(0);
            if (order.getOrderStatic()==1){
                result.setCode(0);
                result.setMsg("支付成功");
                result.setData(0);
                return result;
            }else {
                result.setCode(0);
                result.setMsg("未有变化");
                result.setData(order.getOrderUuid());
                return result;
            }
        }
        return null;
    }

    /**
     * page
     */
    @Override
    public Page<OrderPagePO> pageData(OrderVo orderVo) {
        Page<Order> orderPage = new Page<>(orderVo.getPage(), orderVo.getLimit());
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(orderVo.getFlag())){
            Member member =(Member) SessionUtis.getSessionAttribute("member");
            if (ObjectUtil.isEmpty(member)){
                throw new RuntimeException("用户信息为空");
            }
            wrapper.eq(Order ::getMId,member.getId());
        }
        if (ObjectUtil.isNotEmpty(orderVo.getOrderUuid())){
            wrapper.eq(Order ::getOrderUuid,orderVo.getOrderUuid());
        }
        if (ObjectUtil.isNotEmpty(orderVo.getOrderStatic())){
            wrapper.eq(Order ::getOrderStatic,orderVo.getOrderStatic());
        }
        if (ObjectUtil.isEmpty(orderVo.getFlag())){
            wrapper.eq(Order ::getDeflag,0).orderByDesc(Order::getCreateTime);
        }else{
            wrapper.orderByDesc(Order::getCreateTime);
        }

        Page<Order> page1 = this.page(orderPage, wrapper);
       List<OrderPagePO> orderPagePOList = new ArrayList<>();
        if (page1.getRecords().size()!=0){
            page1.getRecords().forEach(order -> {
                OrderPagePO orderPagePO = new OrderPagePO();
                LambdaQueryWrapper<ExpandOrder> exwrapper = new LambdaQueryWrapper<>();
                exwrapper.eq(ExpandOrder::getOrderId,order.getId());
                exwrapper.eq(ExpandOrder::getDeflag,0);
                List<ExpandOrder> list = expandOrderService.list(exwrapper);
                List<SteamShopingDataPO> steamShopingDataPOList = new ArrayList<>();
                list.forEach(expandOrder -> {
                    SteamShopingDataPO steamShopingDataPO = new SteamShopingDataPO();
                    /**
                     * 商品
                     */
                    Commodity byId = commodityService.getById(expandOrder.getCId());
                    steamShopingDataPO.setImage(byId.getExampleImage1());
                    steamShopingDataPO.setCName(byId.getName());
                    steamShopingDataPO.setCId(byId.getId());
                    /**
                     * 商品规格
                     */
                    SpecsCommodity byid = specsCommdityService.byid(expandOrder.getSpecsId());
                    steamShopingDataPO.setCSku(byid.getCSku());
                    steamShopingDataPO.setPrice(byid.getPrices());
                    steamShopingDataPO.setSpeceId(byid.getId());
                    steamShopingDataPO.setCount(expandOrder.getCount());
                    steamShopingDataPOList.add(steamShopingDataPO);
                });
                AddressVo addressVo = new AddressVo();
                addressVo.setId(order.getAddressId());
                addressVo.setMId(order.getMId());
                List<AddressVo> list1 = addressService.getList(addressVo);

//                //用户信息
//                if (ObjectUtil.isNotEmpty(orderVo.getFlag())){
//                    Member byId = fordMemberService.getById(order.getMId());
//                    orderPagePO.setName(byId.getName());
//                    orderPagePO.setPhone(byId.getPhone());
//                }
                //用户信息
                Member byId1 = fordMemberService.getById(order.getMId());
                if (ObjectUtil.isNotEmpty(byId1)){
                    orderPagePO.setMembetPhone(byId1.getPhone());
                    orderPagePO.setMembetName(byId1.getName());
                }
                orderPagePO.setSteamShopingDataList(steamShopingDataPOList);
                switch (order.getOrderStatic()){
                    case 0:
                        orderPagePO.setOrderStatic("待付款");
                        break;
                    case 1:
                        orderPagePO.setOrderStatic("已付款待发货");
                        break;
                    case 2:
                        orderPagePO.setOrderStatic("已发货");
                        break;
                    case 3:
                        orderPagePO.setOrderStatic("已签收");
                        break;
                    case 4:
                        orderPagePO.setOrderStatic("已评价");
                        break;
                    case 5:
                        orderPagePO.setOrderStatic("待商家同意退款");
                        break;
                    case 6:
                        orderPagePO.setOrderStatic("商家已同意退款申请");
                        break;
                    case 7:
                        orderPagePO.setOrderStatic("商家已驳回退款申请");
                        break;
                    case 8:
                        orderPagePO.setOrderStatic("买家商品已操作退回");
                        break;
                    case 9:
                        orderPagePO.setOrderStatic("售后已完成");
                        break;
                    case 10:
                        orderPagePO.setOrderStatic("订单已删除");
                        break;
                }
                orderPagePO.setStaticSlot(order.getOrderStatic());
                orderPagePO.setOrderId(order.getId());
                orderPagePO.setOrderUUID(order.getOrderUuid());
                orderPagePO.setPrcies(order.getPrice());
                orderPagePO.setCreateTime(order.getCreateTime());
                orderPagePO.setAddress(order.getAddressId());
                orderPagePO.setRegion(list1.get(0).getRegion());
                orderPagePOList.add(orderPagePO);
            });
            Page<OrderPagePO> orderPagePOPage = new Page<>();
            orderPagePOPage.setTotal(page1.getTotal());
            orderPagePOPage.setCurrent(page1.getCurrent());
            orderPagePOPage.setSize(page1.getSize());
            orderPagePOPage.setRecords(orderPagePOList);
            return orderPagePOPage;
        }
        return new Page<OrderPagePO>();
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public String del(Integer id) {
        if (ObjectUtil.isEmpty(id)){
            throw new RuntimeException("id为空");
        }
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order ::getId,id);
        Order order = new Order();
        order.setDeflag(1);
        order.setOrderStatic(10);
        if (this.update(order,wrapper)) {
            return "删除成功";
        }else {
            throw new RuntimeException("删除失败");
        }
    }

    /**
     * 根据ID修改订单状态
     * @param id
     * @param statics
     * @return
     */
    @Override
    @Transactional
    public String byidUpdate(Integer id, Integer statics) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("ID为空");
        }
        if (ObjectUtil.isEmpty(statics)){
            throw new RuntimeException("订单状态为空");
        }
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order ::getId,id);
        Order order = new Order();
        order.setOrderStatic(statics);
        if (this.update(order,wrapper)){
            return "修改成功";
        }else {
            throw new RuntimeException("修改失败");
        }
    }

    /**
     *付款
     * @return
     */
    @Override
    public String pay(Integer id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new RuntimeException("ID为空");
        }
        Member member =(Member) SessionUtis.getSessionAttribute("member");
        if (ObjectUtil.isEmpty(member)){
            throw new RuntimeException("用户信息为空");
        }
        Order order = this.getById(id);
        LambdaQueryWrapper<ExpandOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExpandOrder::getOrderId,id);
        wrapper.eq(ExpandOrder::getDeflag,0);
        List<ExpandOrder> list = expandOrderService.list(wrapper);
        //商品信息
        List<Integer> collect = list.stream().map(ExpandOrder::getCId).collect(Collectors.toList());
        LambdaQueryWrapper<Commodity> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Commodity ::getId,collect);
        wrapper1.eq(Commodity::getDeflag,0);
        List<Commodity> list1 = commodityService.list(wrapper1);
        StringBuilder stringBuilder = new StringBuilder();
        list1.forEach(commodity -> {
            stringBuilder.append(commodity.getName());
        });
        try {
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no",order.getOrderUuid());
            bizContent.put("total_amount",order.getPrice());
            bizContent.put("subject",stringBuilder.toString());
            bizContent.put("body",stringBuilder.toString());
            bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
            String encode = URLEncoder.encode(String.valueOf(member.getId()) , "UTF-8");
            bizContent.put("passback_params", encode);
            String ailpay = ailpay(bizContent);
            return ailpay;
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderByidPo byid(Integer id) {
        OrderByidPo orderByidPo = new OrderByidPo();
        Order order = this.getById(id);
        orderByidPo.setOrder(order);
        //地址信息
        Address byId1 = addressService.getById(order.getAddressId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(byId1.getProvince()+"|").append(byId1.getCity()+"|").append(byId1.getCounty()).append(byId1.getAddress());
        byId1.setAddress(stringBuilder.toString());
        orderByidPo.setAddress(byId1);
        if (order.getOrderStatic()!=0){
            //交易信息
            LambdaQueryWrapper<Pay> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Pay::getOutTradeNo,order.getOrderUuid());
            wrapper.eq(Pay::getDeflag,0);
            List<Pay> list = payService.list(wrapper);
            if (ObjectUtil.isNotEmpty(list)){
                Pay pay = list.get(0);
                orderByidPo.setPay(pay);
            }
        }
        if (order.getOrderStatic()==4) {
            LambdaQueryWrapper<Evaluate> evaluateLambdaQueryWrapper = new LambdaQueryWrapper<>();
            evaluateLambdaQueryWrapper.eq(Evaluate::getOrderId,id);
            evaluateLambdaQueryWrapper.eq(Evaluate::getDeflag,0);
            List<Evaluate> list = evaluateService.list(evaluateLambdaQueryWrapper);
            if (ObjectUtil.isNotEmpty(list)){
                Evaluate evaluate = list.get(0);
                if (ObjectUtil.isNotEmpty(evaluate.getGrade())){
                    switch (evaluate.getGrade()){
                        case 0:
                            orderByidPo.setGrade("好评");
                            break;
                        case 1 :
                            orderByidPo.setGrade("中评");
                            break;
                        case 2 :
                            orderByidPo.setGrade("差评");
                            break;
                    }
                }
                orderByidPo.setText(evaluate.getText());
            }
        }
        //订单商品新
        List<OrderbyidCommtityPo> commtitySpecec = expandOrderMapper.getCommtitySpecec(id);
        orderByidPo.setOrderbyidCommtityPoList(commtitySpecec);
        return orderByidPo;
    }

    /**
     * 修改订单
     * @param orderVo
     * @return
     */
    @Override
    @Transactional
    public String updateDate(OrderVo orderVo) {
        if (ObjectUtil.isEmpty(orderVo.getId())){
            throw new RuntimeException("id为空");
        }
        Order order = new Order();
        BeanUtils.copyProperties(orderVo, order);
        order.setOrderStatic(2);
        if (this.updateById(order)) {
            return "成功";
        }else {
            throw new RuntimeException("失败");
        }
    }
}
